package com.my.lucky.controller;

import com.my.lucky.config.IwencaiConfig;
import com.my.lucky.entity.SysInfo;
import com.my.lucky.repository.SysInfoRepository;
import com.my.lucky.service.IWencaiServiceTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 涨停数据查询控制器
 */
@Slf4j
@Controller
@RequestMapping("/sysinfo")
public class SysInfoController {

    @Autowired
    private SysInfoRepository sysInfoRepository;

    @Autowired
    private IWencaiServiceTools iwencaiService;

    @Autowired
    private IwencaiConfig iwencaiConfig;

    /**
     * 从原始逗号分割字符串中，剔除所有在目标逗号分割字符串中存在的内容
     *
     * @param original 原始字符串（逗号分割）
     * @param toRemove 要剔除的内容（逗号分割）
     * @return 处理后的字符串（逗号分割）
     */
    public static String removeContains(String original, String toRemove) {
        // 处理空值情况
        if (original == null || original.trim().isEmpty()) {
            return original;
        }
        if (toRemove == null || toRemove.trim().isEmpty()) {
            return original; // 要剔除的内容为空，直接返回原始字符串
        }

        // 分割字符串并转换为Set（去重且便于查找）
        Set<String> originalSet = new LinkedHashSet<>(Arrays.asList(original.split(",")));
        Set<String> toRemoveSet = new LinkedHashSet<>(Arrays.asList(toRemove.split(",")));

        // 从原始集合中移除所有需要剔除的元素
        originalSet.removeAll(toRemoveSet);

        // 重新拼接为逗号分割的字符串
        return originalSet.stream()
                .collect(Collectors.joining(","));
    }

    // 使用示例
    public static void main(String[] args) {
        String focusStocks = "科技,消费"; // 要剔除的内容
        String old = "科技,医药,科技,消费,医药,新能源,IT,aigc"; // 原始内容

        String result = removeContains(old, focusStocks);
        System.out.println(result); // 输出：医药,新能源
    }

    /**
     * 处理逗号分隔的字符串，去除重复项
     *
     * @param input 逗号分隔的字符串，可为null或空
     * @return 去重后的逗号分隔字符串，若输入为null或空则返回空字符串
     */
    public static String deduplicateCommaSeparatedString(String input) {
        // 处理空值和空白字符串
        if (input == null || input.trim().isEmpty()) {
            return "";
        }

        // 分割字符串并去重
        Set<String> uniqueElements = new HashSet<>();

        // 按逗号分割，处理可能的空格
        Arrays.stream(input.split(","))
                .map(String::trim)       // 去除每个元素的前后空格
                .filter(s -> !s.isEmpty()) // 过滤空字符串
                .forEach(uniqueElements::add); // 添加到Set自动去重

        // 重新拼接为逗号分隔的字符串
        return uniqueElements.stream()
                .collect(Collectors.joining(","));
    }

    /**
     * 修改信息
     */
    @GetMapping("/update")
    @ResponseBody
    public Map<String, Object> searchLimitUpStocks(
            @RequestParam(required = false) String searchKeyword,
            @RequestParam(required = false) String gainianKeyword,
            @RequestParam(required = false) String focusStocks,
            @RequestParam(required = false) String allOptional,
            @RequestParam(required = false) String focusGainian) {
        try {
            sysInfoRepository.updateByKey("searchKeyword", searchKeyword);
            sysInfoRepository.updateByKey("gainianKeyword", gainianKeyword);
            sysInfoRepository.updateByKey("focusStocks", deduplicateCommaSeparatedString(focusStocks));
            sysInfoRepository.updateByKey("focusGainian", focusGainian);
            sysInfoRepository.updateByKey("allOptional", allOptional);
            iwencaiService.init();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return response;
        } catch (Exception e) {
            log.error("修改信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "修改信息失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 添加信息
     */
    @GetMapping("/appendBy")
    @ResponseBody
    public Map<String, Object> appendByKey(
            @RequestParam(required = false) String focusStocks,
            @RequestParam(required = false) String allOptional,
            @RequestParam(required = false) String focusGainian) {
        try {
            if (focusStocks != null && !focusStocks.trim().isEmpty()) {
                sysInfoRepository.appendByKey("focusStocks", "," + deduplicateCommaSeparatedString(focusStocks));
            }
            if (focusGainian != null && !focusGainian.trim().isEmpty()) {
                sysInfoRepository.appendByKey("focusGainian", "," + focusGainian);
            }
            if (allOptional != null && !allOptional.trim().isEmpty()) {
                sysInfoRepository.appendByKey("allOptional", "," + deduplicateCommaSeparatedString(allOptional));
                sysInfoRepository.appendByKey("focusStocks", "," + deduplicateCommaSeparatedString(allOptional));
//                System.out.println("allOptional====");
            }
            iwencaiService.init();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return response;
        } catch (Exception e) {
            log.error("添加信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "添加信息失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 取消信息
     */
    @GetMapping("/removeBy")
    @ResponseBody
    public Map<String, Object> removeByKey(
            @RequestParam(required = false) String focusStocks,
            @RequestParam(required = false) String focusGainian) {
        try {
            if (focusStocks != null && !focusStocks.trim().isEmpty()) {
                String old = iwencaiConfig.getFocus();
                sysInfoRepository.updateByKey("focusStocks", deduplicateCommaSeparatedString(removeContains(old, focusStocks)));

                String allOptional = iwencaiConfig.getAllOptional();
                sysInfoRepository.updateByKey("allOptional", deduplicateCommaSeparatedString(removeContains(allOptional, focusStocks)));
            }
            if (focusGainian != null && !focusGainian.trim().isEmpty()) {
                String old = iwencaiConfig.getFocusGaiNian();
                sysInfoRepository.updateByKey("focusGainian", removeContains(old, focusGainian));
            }
            iwencaiService.init();
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            return response;
        } catch (Exception e) {
            log.error("取消信息失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "取消信息失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 更新时间配置
     */
    @PostMapping("/updateTimeConfig")
    @ResponseBody
    public Map<String, Object> updateTimeConfig(@RequestBody TimeConfig timeConfig) {
        try {
            // 保存各个时间配置项
            sysInfoRepository.updateByKey("morningStart", timeConfig.getMorningStart());
            sysInfoRepository.updateByKey("morningEnd", timeConfig.getMorningEnd());
            sysInfoRepository.updateByKey("afternoonStart", timeConfig.getAfternoonStart());
            sysInfoRepository.updateByKey("afternoonEnd", timeConfig.getAfternoonEnd());
            sysInfoRepository.updateByKey("enableTimeControl", timeConfig.getEnableTimeControl() != null ? timeConfig.getEnableTimeControl().toString() : "false");

            log.info("时间配置更新成功: {}", timeConfig);

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "时间配置保存成功");
            iwencaiService.init();
            return response;
        } catch (Exception e) {
            log.error("时间配置保存失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "时间配置保存失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 获取策略列表
     */
    @GetMapping("/getCheckSys")
    @ResponseBody
    public Map<String, Object> getCheckSys() {
        try {
            // 保存各个时间配置项
            iwencaiService.init();
            List<SysInfo> checksysInfos = iwencaiConfig.getChecksysInfos();
            log.info("getCheckSys: {}" + checksysInfos, checksysInfos);
            Map<String, Object> response = new HashMap<>();
            response.put("checksysInfos", checksysInfos);
            response.put("success", true);
            response.put("message", "获取策略列表成功");
            return response;
        } catch (Exception e) {
            log.error("获取策略列表失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取策略列表失败: " + e.getMessage());
            return response;
        }
    }

    /**
     * 时间配置数据类
     */
    public static class TimeConfig {
        private String morningStart;
        private String morningEnd;
        private String afternoonStart;
        private String afternoonEnd;
        private Boolean enableTimeControl;

        // 构造函数
        public TimeConfig() {
        }

        // Getter和Setter方法
        public String getMorningStart() {
            return morningStart;
        }

        public void setMorningStart(String morningStart) {
            this.morningStart = morningStart;
        }

        public String getMorningEnd() {
            return morningEnd;
        }

        public void setMorningEnd(String morningEnd) {
            this.morningEnd = morningEnd;
        }

        public String getAfternoonStart() {
            return afternoonStart;
        }

        public void setAfternoonStart(String afternoonStart) {
            this.afternoonStart = afternoonStart;
        }

        public String getAfternoonEnd() {
            return afternoonEnd;
        }

        public void setAfternoonEnd(String afternoonEnd) {
            this.afternoonEnd = afternoonEnd;
        }

        public Boolean getEnableTimeControl() {
            return enableTimeControl;
        }

        public void setEnableTimeControl(Boolean enableTimeControl) {
            this.enableTimeControl = enableTimeControl;
        }
    }

} 